<template>
  <el-dialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="600px"
    @update:model-value="handleClose"
  >
    <el-form :model="brandForm" :rules="formRules" ref="formRef" label-width="100px">
      <el-form-item label="品牌编码" prop="code">
        <el-input v-model="brandForm.code" placeholder="请输入品牌编码" />
      </el-form-item>
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="brandForm.name" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="英文名称">
        <el-input v-model="brandForm.enName" placeholder="请输入英文名称" />
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="brandForm.sortNum" :min="0" style="width: 100%" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="brandForm.state">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="-1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="品牌Logo">
        <div class="logo-upload">
          <el-input 
            v-model="brandForm.logo" 
            placeholder="请输入品牌Logo的URL地址"
            clearable
          />
          <div v-if="brandForm.logo" class="logo-preview">
            <el-image
              :src="brandForm.logo"
              fit="contain"
              style="width: 100px; height: 100px"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="品牌描述">
        <el-input v-model="brandForm.description" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import {post} from "@/utils/request.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref()

const brandForm = reactive({
  id: null,
  code: '',
  name: '',
  enName: '',
  sortNum: 0,
  state: 1,
  description: '',
  logo: ''
})

const formRules = {
  code: [{ required: true, message: '请输入品牌编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }]
}

const isEdit = computed(() => !!brandForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑品牌' : '新增品牌')

// 重置表单
const resetForm = () => {
  Object.assign(brandForm, {
    id: null,
    code: '',
    name: '',
    enName: '',
    sortNum: 0,
    state: 1,
    description: '',
    logo: ''
  })
  formRef.value?.clearValidate()
}

// 监听传入的数据，初始化表单
watch(() => props.data, (newData) => {
  if (newData) {
    Object.assign(brandForm, { ...newData })
  } else {
    resetForm()
  }
}, { immediate: true })

const handleClose = () => {
  emit('update:modelValue', false)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    // 根据是否编辑状态调用不同接口
    const url = isEdit.value ? '/brand/update' : '/brand/create'
    let res = await post(url, brandForm);

    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return;
    }

    // 调用成功
    emit('success', { ...brandForm })
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    handleClose()
  } catch (error) {
    // 验证失败或接口调用失败
    console.log('提交失败', error)
  }
}
</script>

<style scoped>
.logo-upload {
  width: 100%;
}

.logo-preview {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: inline-block;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 30px;
  margin-bottom: 5px;
}
</style>

